'use strict';

const uniID = require('uni-id')
const uniCaptcha = require('uni-captcha')
const db = uniCloud.database()
const dbCmd = db.command
exports.main = async (event, context) => {
	/* 如果你通过云函数Url访问
	 * 使用GET时参数位于event.queryStringParameters
	 * 使用POST时参数位于event.body
	 * 请自行处理上述场景
	 */
	let params = event.params || {}
	let payload = {}
	let noCheckAction = ['register', '','checkToken', 'encryptPwd', 'login', 'loginByWeixin', 'sendSmsCode',
		'setVerifyCode', 'loginBySms','verifyCaptcha', 'loginByEmail','forgetPassword','createCaptcha',
		 'code2SessionWeixin', 'forgetPasswordCaptcha','code2SessionAlipay','refreshCaptcha'
	]
	// 登录记录
	const loginLog = async (res = {}, type = 'login') => {
		const now = Date.now()
		const uniIdLogCollection = db.collection('uni-id-log')
		let logData = {
			deviceId: params.deviceId || context.DEVICEID,
			ip: params.ip || context.CLIENTIP,
			type,
			ua: context.CLIENTUA,
			create_date: now
		};
	
		Object.assign(logData,
			res.code === 0 ? {
				user_id: res.uid,
				state: 1
			} : {
				state: 0
			})
	
		return uniIdLogCollection.add(logData)
	}
	const getNeedCaptcha = async () => {
		const now = Date.now()
		// 查询是否在 {2小时} 内 {前2条} 有 {登录失败} 数据，来确定是否需要验证码
		const recordSize = 2;
		const recordDate = 120 * 60 * 1000;
	
		const uniIdLogCollection = db.collection('uni-id-log')
		let recentRecord = await uniIdLogCollection.where({
				deviceId: params.deviceId || context.DEVICEID,
				create_date: dbCmd.gt(now - recordDate),
				type: 'login'
			})
			.orderBy('create_date', 'desc')
			.limit(recordSize)
			.get();
	
		return recentRecord.data.filter(item => item.state === 0).length === recordSize;
	}
	console.log(noCheckAction,event.action,noCheckAction.indexOf(event.action) === -1)
	if (noCheckAction.indexOf(event.action) === -1) {
		if (!event.uniIdToken) {
			return {
				code: 403,
				msg: '缺少token'
			}
		}
		payload = await uniID.checkToken(event.uniIdToken, {
			needPermission: true
		})
		console.log(payload)
		if (payload.code && payload.code > 0) {
			return payload
		}
		params.uid = payload.uid
	}
	let res = {}

	switch (event.action) {
		case 'getUserInfo':
		{
			res = await uniID.getUserInfo({
				uid: payload.uid
			})
			break;
		}
		case 'verifyCaptcha':
			res = await uniCaptcha.verify(params)
			break;
		case 'createCaptcha':
			res = await uniCaptcha.create(params)
			break;
		case 'refreshCaptcha':
			res = await uniCaptcha.refresh(params)
			break;
		case 'forgetPassword':
		{
			res = await db.collection('opendb-verify-codes').where({
				mobile: params.username,
				code: params.captcha,
				type:"forgetPassword"
				// ,expired_at:dbCmd.gt(Date.now())
			}).get()
			console.log(res.data.length)
			if(res.data.length>0){
				let {data:users}=await db.collection('uni-id-users').where({username:params.username}).get()
				res = await uniID.resetPwd({
					uid: users[0]._id,
					password:params.newPassword
				})
			}
			break;
		}
		case 'forgetPasswordCaptcha':
		{
			if (!/^1\d{10}$/.test(params.username)) {
				return {
					code: 500,
					msg: '手机号码填写错误'
				}
			}
			let r = await uniCaptcha.refresh(params)
			let code=r.code
			console.log(r)
			if(code==0){
				// 简单限制一下客户端调用频率
				const ipLimit = await db.collection('opendb-verify-codes').where({
					ip: context.CLIENTIP,
					created_at: dbCmd.gt(Date.now() - 60000)
				}).get()
				if (ipLimit.data.length > 0) {
					return {
						code: 403,
						msg: '请求过于频繁'
					}
				}
				const templateId = '11708'
				const randomStr = '00000' + Math.floor(Math.random() * 1000000)
				const code = randomStr.substring(randomStr.length - 6)
				res = await uniID.sendSmsCode({
					mobile:params.username,
					code,
					expMinute: '3',
					type:'forgetPassword',
					templateId
				});
				break;
			}else{
				res={
					code: 403,
					msg: '验证码错误'
				}
			}
			break;
		}
		case 'updatePwd':
			res = await uniIDIns.updatePwd({
				uid: params.uid,
				...params
			})
			break;
		case 'register':
			{
				const {
					username,
					password,
					needPermission
				} = params
				res = await uniID.register({
					username,
					password,
					needPermission
				});
				break;
			}
		case 'login':
			{
				const {
					username,
					password
				} = params
				res = await uniID.login({
					username,
					password,
					// 不指定queryField的情况下只会查询username
					queryField: ['username', 'email', 'mobile']
				});
				break;
			}
		case 'logout':
			res = await uniID.logout(event.uniIdToken);
			break;
		case 'updatePwd':
			{
				const {
					uid,
					oldPassword,
					newPassword
				} = params
				res = await uniID.updatePwd({
					uid,
					oldPassword,
					newPassword
				});
				break;
			}
		case 'setAvatar':
			{
				const {
					uid,
					avatar
				} = params
				res = await uniID.setAvatar({
					uid,
					avatar
				});
				break;
			}
		case 'bindMobile':
			{
				const {
					uid,
					mobile,
					code
				} = params
				res = await uniID.bindMobile({
					uid,
					mobile,
					code
				});
				break;
			}
		case 'unbindMobile':
			{
				const {
					uid,
					mobile,
					code
				} = params
				res = await uniID.unbindMobile({
					uid,
					mobile,
					code
				});
				break;
			}
		case 'bindEmail':
			{
				const {
					uid,
					email,
					code
				} = params
				res = await uniID.bindEmail({
					uid,
					email,
					code
				});
				break;
			}
		case 'unbindEmail':
			{
				const {
					uid,
					email,
					code
				} = params
				res = await uniID.unbindEmail({
					uid,
					email,
					code
				});
				break;
			}
		case 'code2SessionWeixin':
			{
				const {
					code
				} = params
				res = await uniID.code2SessionWeixin({
					code
				});
				break;
			}
		case 'loginByWeixin':
			{
				const {
					code,
					invitation
				} = params
				
				res = await uniID.loginByWeixin({
					code
				});
				if(res.type=='register'){
					let re =await uniID.updateUser({
						invitation,
						uid:res.uid,
						integral:100,
						promotionNumber:0
					});
					console.log(re)
					if(invitation){
						console.log("邀请码")
						console.log(invitation)
						const db = uniCloud.database()
						const dbCmd = db.command
						await db.collection('uni-id-users').where({
						  _id: invitation
						}).update({
							promotionNumber: dbCmd.inc(1),
						  integral: dbCmd.inc(100)
						})
					}
				}
				break;
			}
		case 'bindWeixin':
			{
				const {
					uid,
					code
				} = params
				res = await uniID.bindWeixin({
					uid,
					code
				});
				break;
			}
		case 'unbindWeixin':
			res = await uniID.unbindWeixin(params.uid);
			break;
		case 'code2SessionAlipay':
			{
				const {
					code
				} = params
				res = await uniID.code2SessionAlipay({
					code
				});
				break;
			}
		case 'loginByAlipay':
			{
				const {
					code
				} = params
				res = await uniID.loginByAlipay({
					code
				});
				break;
			}
		case 'bindAlipay':
			{
				const {
					uid,
					code
				} = params
				res = await uniID.bindAlipay({
					uid,
					code
				});
				break;
			}
		case 'unbindAlipay':
			{
				res = await uniID.unbindAlipay(params.uid);
				break;
			}
		case 'checkToken':
			// 注意3.0.0版本取消了checkToken接口返回的用户信息
			res = await uniID.checkToken(event.uniIdToken, {
				needPermission: true
			})
			break;
		case 'resetPwd':
			res = await uniID.resetPwd({
				uid: params.uid,
				password: '123456'
			});
			break;
		case 'encryptPwd':
			const password = await uniID.encryptPwd('123456');
			res = {
				code: 0,
				msg: '密码加密完成',
				password
			}
			break;
		case 'sendSmsCode':
			{
				const {
					mobile,
					code,
					type
				} = params
				const templateId = ''
				if (templateId === '') {
					throw new Error('sendSmsCode接口需要传入templateId来指定所使用的短信模板')
				}
				res = await uniID.sendSmsCode({
					mobile,
					code,
					type,
					templateId
				});
				break;
			}
		case 'setVerifyCode':
			{
				const {
					mobile,
					code,
					type
				} = params
				res = await uniID.setVerifyCode({
					mobile,
					code,
					type
				});
				break;
			}
		case 'loginBySms':
			{
				const {
					mobile,
					code
				} = params
				res = await uniID.loginBySms({
					mobile,
					code
				});
				break;
			}
		case 'loginByEmail':
			{
				const {
					email,
					code
				} = params
				res = await uniID.loginByEmail({
					email,
					code
				});
				break;
			}
		case 'updateUser':
			{
				res = await uniID.updateUser(params);
				break;
			}
		case 'setUserInviteCode':
			{
				const {
					uid,
					// myInviteCode 不指定myInviteCode，自动获取
				} = params
				res = await uniID.setUserInviteCode({
					uid
				});
				break;
			}
		case 'acceptInvite':
			{
				const {
					uid,
					inviteCode
				} = params
				res = await uniID.acceptInvite({
					uid,
					inviteCode
				});
				break;
			}
		case 'addRole':
			{
				const {
					roleID,
					roleName,
					comment,
					permission
				} = params
				res = await uniID.addRole({
					roleID,
					roleName,
					comment,
					permission
				});
				break;
			}
		case 'getRoleList':
			{
				const {
					offset,
					limit,
					needTotal
				} = params
				res = await uniID.getRoleList({
					offset,
					limit,
					needTotal
				});
				break;
			}
		case 'addPermission':
			{
				const {
					permissionID,
					permissionName,
					comment
				} = params
				res = await uniID.addPermission({
					permissionID,
					permissionName,
					comment
				});
				break;
			}
		case 'getPermissionList':
			{
				const {
					offset,
					limit,
					needTotal
				} = params
				res = await uniID.getPermissionList({
					offset,
					limit,
					needTotal
				});
				break;
			}
		case 'getRoleByUid':
			{
				const {
					uid
				} = params
				res = await uniID.getRoleByUid({
					uid
				});
				break;
			}
		case 'bindRole':
			{
				const {
					roleList,
					// 设置reset为true，整体覆盖。设置为false时增量更新role
					reset,
				} = params
				res = await uniID.bindRole({
					roleList,
					reset,
				});
				break;
			}
		case 'bindPermission':
			{
				const {
					roleID,
					permissionList,
					// 设置reset为true，整体覆盖。设置为false时增量更新role
					reset,
				} = params
				res = await uniID.bindPermission({
					roleID,
					permissionList,
					reset,
				});
				break;
			}
		default:
			res = {
				code: 403,
				msg: '非法访问'
			}
			break;
	}

	//返回数据给客户端
	return res
};
